package com.ddxz.middleground.meta.collect;

import com.ddxz.tool.sql.exception.DdxzSqlException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;

import static com.ddxz.middleground.meta.util.ErrorStatus.SOURCE_NOT_VALID;

/**
 * class description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2020/8/23
 */

public abstract class BaseDataSourceCollect {
    /**
     * 首先判断IP地址是否可用；
     * 其次测试JDBC连接是否正常；
     * 最后执行一个默认的SQL语句
     * @return
     */
    public boolean isValid() {
        try {
            InetAddress address = InetAddress.getByName(host);
            if(!address.isReachable(TIMEOUT)) {
                throw new DdxzSqlException(SOURCE_NOT_VALID);
            }
        } catch (Exception e) {
            logger.error(SOURCE_NOT_VALID.getMessage(), e);
            throw new DdxzSqlException(SOURCE_NOT_VALID);
        }

        getConnection();
        return true;
    }

    protected abstract void getConnection();


    protected BaseDataSourceCollect(String host, Integer port, String instance, String user, String password) {
        this.host = host;
        this.port = port;
        this.instance = instance;
        this.user = user;
        this.password = password;
    }

    protected final String host;

    protected final Integer port;

    protected final String instance;

    protected final String user;

    protected final String password;

    private static final Logger logger = LoggerFactory.getLogger(BaseDataSourceCollect.class);

    private static final int TIMEOUT = 1000;
}
